package com.sgzn.sgpay.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayOutputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

/**
 * Created by Chenkh on 2015/6/16.
 */
@Slf4j
public class Base64Util {

    /**
     * 压缩字符串
     *
     * @param text
     * @return
     */
    public static String zip(String text) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DeflaterOutputStream zos = new DeflaterOutputStream(bos);
            zos.write(text.getBytes());
            zos.close();
            return genBase64Encode(bos.toByteArray());
        } catch (Exception ex) {
            log.error("进行Base64压缩字符串时发生异常，详细信息：\n{}", ex);
            return null;
        }
    }


    /**
     * 解码字符串
     *
     * @param zipText
     * @return
     */
    public static String unzip(String zipText) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            InflaterOutputStream zos = new InflaterOutputStream(bos);
            zos.write(deCodeByBase64(zipText));
            zos.close();
            return new String(bos.toByteArray());
        } catch (Exception ex) {
            log.error("进行Base64解压缩字符串时发生异常，详细信息：\n{}", ex);
            return null;
        }
    }

    /**
     * 使用apche codec对数组进行encode
     *
     * @param b
     * @return
     */
    public static String genBase64Encode(byte[] b) {
        if (null == b) {
            return null;
        }
        return Base64.encodeBase64String(b);
    }


    /**
     * base64转码为string
     *
     * @param s
     * @return
     */
    public static byte[] deCodeByBase64(String s) {
        if (s == null) {
            return null;
        }
        return new Base64().decode(s.getBytes());
    }

}
